// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Y [author] rhyme_lph
// G [email]  rhymelph@gmail.com
// a [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/app_spaces.dart';
import 'package:finance_app/src/common/config.dart';
import 'package:finance_app/src/entities/coa_entity.dart';
import 'package:finance_app/src/provider/setting/account/new_account_provider.dart';
import 'package:finance_app/src/router_gen/router_meta.dart';
import 'package:finance_app/src/utils/date_time_utils.dart';
import 'package:finance_app/src/widgets/button/normal_popup_button.dart';
import 'package:finance_app/src/widgets/button/normal_text_button.dart';
import 'package:finance_app/src/widgets/common_app_bar.dart';
import 'package:finance_app/src/widgets/form/account_add_form.dart';
import 'package:finance_app/src/widgets/form/form_edit_status_inherited_widget.dart';
import 'package:finance_app/src/widgets/form/text_area_input_form.dart';
import 'package:finance_app/src/widgets/form/title_currency_price_input_form.dart';
import 'package:finance_app/src/widgets/form/value_select_form.dart';
import 'package:finance_app/src/widgets/input/form_input_field.dart';
import 'package:flutter/material.dart';
import 'package:tuple/tuple.dart';

export 'package:finance_app/src/entities/coa_entity.dart';

@RouterMeta(paramName: "newAccountPage")
class NewAccountPage extends StatefulWidget {
  final CoaCoaAccountHeaderCoaAccountDetail data;
  final CoaCoaAccountHeaderCoaAccountDetail parentData;

  const NewAccountPage({Key key, this.data, this.parentData}) : super(key: key);

  @override
  _NewAccountPageState createState() => _NewAccountPageState();
}

class _NewAccountPageState extends State<NewAccountPage>
    with PagePresenter<NewAccountPage, NewAccountProvider> {
  String get title => provider.id == null
      ? S.current.new_subaccount
      : provider.isEdit == true
          ? S.current.edit_subaccount
          : S.current.subaccount;

  Widget get rightButton => listBuilder<bool>(
        selector: (_, __) => __.isEdit,
        builder: (BuildContext context, bool value, Widget child) =>
            provider.id != null && provider.isEdit == false
                ? _buildPopButton()
                : _buildSaveBtn(),
      );

  @override
  PreferredSizeWidget get appBar => getDefaultAppBar(
          titleWidget: listBuilder<bool>(
            selector: (_, __) => __.isEdit,
            builder: (BuildContext context, bool value, Widget child) =>
                Text(title),
          ),
          actions: [
            rightButton,
          ]);

  Widget _buildPopButton() => listBuilder<bool>(
        selector: (_, __) =>
            (provider.id != null && __.isEdit) ||
            (widget.data?.editDisallowed ?? false),
        builder: (BuildContext context, bool value, Widget child) =>
            value == true
                ? Container()
                : NormalMorePopupButton(
                    onSelect: provider.onSelectMenu,
                    menuList: provider.menuList,
                  ),
      );

  Widget _buildSaveBtn() {
    return listBuilder<bool>(
      selector: (_, __) => pageStatus != PageStatus.loading,
      builder: (BuildContext context, bool value, Widget child) => value == true
          ? NormalSaveTextButton(
              onTap: provider.onSave,
            )
          : Container(),
    );
  }

  @override
  void initState() {
    provider.asAt =
        DateTimeUtils.toDateTime(Config.currentFY.startDate, 'yyyy-MM-dd');
    provider.unit = Config.defaultCurrency;
    provider.initWidgetData(widget.data, widget.parentData);
    super.initState();
  }

  @override
  Widget wrapperBody(Widget child) {
    return listBuilder<bool>(
      selector: (_, __) => __.isEdit == true || provider.id == null,
      builder: (BuildContext context, bool value, Widget child) =>
          FormEditStatusInheritedWidget(
        isEdit: value,
        child: child,
      ),
      child: child,
    );
  }

  @override
  Widget get buildWidget => ColoredBox(
        color: Colors.white,
        child: ListView(
          children: [
            FromInputField(
              controller: provider.accountNameController,
              focusNode: provider.accountNameFocusNode,
              tip: S.current.subaccount_name,
            ),
            listBuilder<bool>(
              selector: (_, __) => __.parentAccount?.id == 0,
              builder: (BuildContext context, bool visible, Widget child) =>
                  listBuilder<Tuple2<String, bool>>(
                selector: (_, __) => Tuple2<String, bool>(
                    __.parentAccount?.name, __.isEdit ?? false),
                builder: (BuildContext context, Tuple2<String, bool> value,
                        Widget child) =>
                    Visibility(
                  visible: !visible,
                  child: ValueSelectForm(
                    title: S.current.parent_account,
                    value: value.item1,
                    onTap: value.item2 ? null : provider.onChangeParentAccount,
                  ),
                ),
              ),
            ),
            listBuilder<Tuple2<bool, bool>>(
              selector: (_, __) =>
                  Tuple2<bool, bool>(__.numberHasError, __.isEdit ?? false),
              builder: (BuildContext context, Tuple2<bool, bool> value,
                      Widget child) =>
                  value.item2
                      ? ValueSelectForm(
                          title: S.current.account_code,
                          value: provider.accountCodeController.text,
                        )
                      : FromInputField(
                          controller: provider.accountCodeController,
                          focusNode: provider.accountCodeFocusNode,
                          keyboardType:
                              TextInputType.numberWithOptions(decimal: true),
                          tip: S.current.account_code,
                          hasError: value.item1,
                        ),
            ),
            listBuilder<Tuple2<String, bool>>(
              selector: (_, __) =>
                  Tuple2<String, bool>(__.unit?.name, __.isEdit ?? false),
              builder: (BuildContext context, Tuple2<String, bool> value,
                      Widget child) =>
                  ValueSelectForm(
                title: S.current.currency,
                value: value.item1,
                onTap: value.item2 ? null : provider.onChangeCurrency,
                border: null,
              ),
            ),
            listBuilder<Tuple2<bool, int>>(
              selector: (_, __) =>
                  Tuple2(__.isShowProductLink, __.productList.length),
              builder: (BuildContext context, Tuple2<bool, int> value,
                      Widget child) =>
                  Visibility(
                      visible: value.item1,
                      child: AccountAddForm(
                        title: S.current.linked_products,
                        count: value.item2,
                        onLinked: provider.onLinkedProducts,
                      )),
            ),
            listBuilder<Tuple2<bool, int>>(
              selector: (_, __) =>
                  Tuple2(__.isShowServiceLink, __.serviceList.length),
              builder: (BuildContext context, Tuple2<bool, int> value,
                      Widget child) =>
                  Visibility(
                      visible: value.item1,
                      child: AccountAddForm(
                        title: S.current.linked_services,
                        count: value.item2,
                        onLinked: provider.onLinkedService,
                      )),
            ),
            AppSpaces.grayH6,
            TextAreaInputForm(
              title: S.current.account_description_Optional,
              controller: provider.accountDescriptionController,
              focusNode: provider.accountDescriptionFocusNode,
            ),
          ],
        ),
      );
}
